let User = require("../model/user.js");

// 中间件函数  -> 在中间件中使用
function validateRegParams(req, res, next) {
    // 验证参数
    let body = req.body;
    let { user, pwd, phone, email } = body;
    console.log(body);
    if (user && pwd && phone && email) {
      next();
    } else {
      let obj = {
        status: false,
        message: "Fail",
        reason: "请传入完整参数",
      }
      res.json(obj);
    }
  }
  
  function validateUser(req, res, next) {
    // if(req.methods == "get"){
    //     var {user} = req.query;
    // }else{
    //     var {user} = req.body;
    // }
    var {user} = req.method.toLowerCase() == "get" ?  req.query :  req.body;
    console.log(11111, req.method.toLowerCase());
    User.findOne({ user: user }).then((info) => {
      console.log("用户名是否存在", info);
      if (!info) {  // 用户名可以用 => 验证手机号
        next();
      } else {
        let obj = {
          status: false,
          message: "该用户已被注册",
        }
        res.json(obj);
      }
  
    }).catch(err => {
      let obj = {
        status: false,
        message: "Fail",
        reason: err.message,
      }
      res.json(obj);
    })
  }
  
  function validatePhone(req, res, next) {
    let {phone} = req.method.toLowerCase() == "get" ?  req.query :  req.body;
    ;
    User.findOne({ phone: phone }).then((info) => {
      console.log("手机号是否存在", info);
      if (!info) {  // 手机号可以用 => 验证邮箱
        next();
      } else {
        let obj = {
          status: false,
          message: "该手机号已被注册",
        }
        res.json(obj);
      }
  
    }).catch(err => {
      let obj = {
        status: false,
        message: "Fail",
        reason: err.message,
      }
      res.json(obj);
    })
  }
  
  function validateEmail(req, res, next) {
    let {email} = req.method.toLowerCase() == "get" ?  req.query :  req.body;
    User.findOne({ email: email }).then((info) => {
      console.log("邮箱是否存在", info);
      if (!info) {  // 邮箱可以用 => 注册
        next();
      } else {
        let obj = {
          status: false,
          message: "该邮箱已被注册",
        }
        res.json(obj);
      }
  
    }).catch(err => {
      let obj = {
        status: false,
        message: "Fail",
        reason: err.message,
      }
      res.json(obj);
    })
  }
  

module.exports = {
    validateRegParams,
    validateUser,
    validatePhone,
    validateEmail,
}